// pages/movies/movies.js
var util = require('../../utils/utils.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    containerShow: true,
    searchPanel: false,
    searchResult: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var inTheatersURL = app.globalData.doubanBase + '/v2/movie/in_theaters' + '?start=0&count=3'
    var comingSoonURL = app.globalData.doubanBase + '/v2/movie/coming_soon' + '?start=0&count=3'
    var top250URL = app.globalData.doubanBase + '/v2/movie/top250' + '?start=0&count=3'
    this.getMovieListData(inTheatersURL, 'inTheaters', '正在热映')
    this.getMovieListData(comingSoonURL, 'comingSoon', '即将上映')
    this.getMovieListData(top250URL, 'top250', '豆瓣Top250')
  },
  onMovieTap(event) {
    // console.log(event)
    var id = event.currentTarget.dataset.movieid
    wx.navigateTo({
      url: "/pages/movies/movie-detail/movie-detail?id=" + id
    })
  },
  onMoreTap(event) {
    var category = event.currentTarget.dataset.category
    wx.navigateTo({
      url: "/pages/movies/more-movie/more-movie?category=" + category
    })
    // console.log(event)
  },
  getMovieListData(url, settedKey, categoryTitle) {
    wx.request({
      url: url,
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        this.processDoubanData(res.data, settedKey, categoryTitle)
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },
  onBindFocus(event) {
    // console.log('focus')
    this.setData({
      containerShow: false,
      searchPanel: true
    })
  },
  onBindBlur(event) {
    // console.log('blur')
    var SearchText = event.detail.value
    // console.log(SearchText)
    var searchUrl = app.globalData.doubanBase + '/v2/movie/search?q=' + SearchText
    this.getMovieListData(searchUrl, 'searchResult', '')
    wx.showNavigationBarLoading()
  },
  onCancelImgTap() {
    this.setData({
      containerShow: true,
      searchPanel: false,
      searchResult: {}
    })
  },
  processDoubanData(moviesDouban, settedKey, categoryTitle) {
    // console.log(moviesDouban)
    var movies = []
    for (const idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx]
      var title = subject.title
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...'
      }
      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp)
    }
    var readyData = {}
    readyData[settedKey] = {
      categoryTitle: categoryTitle,
      movies: movies
    }
    this.setData(readyData)
    wx.hideNavigationBarLoading()
  }
})